#include <iostream>
#include <cmath>

using namespace std;

class Function {
public:
    virtual double operator () (double x) = 0;
};

class SecantSolver {
protected:
    Function &F;
public:
    SecantSolver(Function &F) : F(F) {}

    double solve(double x0, double x1) {
        const int max_calls = 30;
        const double tolerance_x = 1e-10;
        const double tolerance_y = 1e-12;

        double fx0 = F(x0); 
        double fx1 = F(x1); 

        // 如果初始函數值很接近，则无法用割线法进行有效迭代，对这种情况进行处理
        if (fabs(fx1 - fx0) < 1e-15) {
            // 对这种情况进行警告
            cout << "Warning: Initial function values are too close, stopping." << endl;
            return x1;
        }

        double x_new;
        double fx_new;

        for (int i = 2; i < max_calls; ++i) {
            // 割线法迭代公式
            x_new = x1 - fx1 * (x1 - x0) / (fx1 - fx0);
            fx_new = F(x_new); 

            // 检查收敛条件
            if (fabs(x_new - x1) < tolerance_x || fabs(fx_new) < tolerance_y) {
                return x_new;
            }

            // 更新迭代值
            x0 = x1;
            fx0 = fx1;
            x1 = x_new;
            fx1 = fx_new;
            
        }

        // 达到最大调用次数，返回最后的值
        return x1;
    }
};


